package lc;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.util.Properties;

import org.junit.Test;

public class Ex340 {
    class Solution {
        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            int max = k, n = s.length();
            char[] cs = s.toCharArray();
            int cnt = 0, lo = 0, hi = 0;
            int[] map = new int[n];
            int idx;

            while (hi < n) {
                while (hi < n && cnt < k) {
                    idx = cs[hi] - 'a';
                    if (map[idx] == 0) {
                        cnt++;
                    }
                    map[idx]++;
                    hi++;
                }
                if (cnt < k) {
                    return max;
                }
                // while (lo < hi && map[(idx = cs[lo] - 'a')] > 1) {
                //     map[idx]--;
                //     lo++;
                // }
                if (hi - lo + 1 > max) {
                    System.out.println(s.substring(lo, hi - lo + 1));
                }
                max = Math.max(max, hi - lo + 1);
                while (cnt == k) {
                    idx = cs[lo] - 'a';
                    map[idx]--;
                    lo++;
                    if (map[idx] == 0) {
                        cnt--;
                    }
                }
            }
            return max;
        }
    }

    @Test
    public void test() {
        // Solution s = new Solution();
        // System.out.println(s.lengthOfLongestSubstringKDistinct("aa", 1)); 
        
        
        InputStream is = Ex340.class.getResourceAsStream("/res/t.txt");
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            //TODO: handle exception
        }
    }

    @Test
    public void test2() {
        Solution s = new Solution();
        try {
            Properties prop = new Properties();
            prop.load(Ex340.class.getClassLoader().getResourceAsStream("res/a.txt"));
            String classname =  prop.getProperty("classname");
            Class<?> clazz = Class.forName(classname);
            Constructor<?> cons = clazz.getDeclaredConstructor();
            Ex14 ex14 = (Ex14) cons.newInstance(null);
            System.out.println(ex14);
            System.out.println("finish");
        } catch (Exception e) {
            e.printStackTrace();
        }

        
    }
}
